#include<iostream>
#include<unistd.h>
#include<stdlib.h>
#include<string>
#include<sys/types.h>
#include<sys/wait.h>

void Write(int p, const std::string s)
{
  std::string temp = " 子进程pid-> ";
  pid_t id = getpid();
  temp += std::to_string(id);
  temp += s;
  write(p, temp.c_str(), temp.size());

}

void Read(int p)
{
  std::string ans;
  pid_t id = getpid();
  char arr[1024] = {'\0'};
  while (read(p, arr, 1))
  {
    ans += arr;
    arr[0] = '\0';
  }
  ans += " 父进程pid-> ";
  ans += std::to_string(id);
  std::cout << ans << std::endl; 
}

int main()
{
  int p[2] = {0};
  int n = pipe(p);

  if (n == -1)
  {
    perror("pipe make errno");
    return -1;
  }

  std::cout << "read->" << p[0] << " " << "write->" << p[1] << std::endl;

  //child->write parent->read 
  pid_t id = fork();
  if (id < 0)
  {
    perror("fork make errno");
    return 2;
  }
  else if (id == 0)
  {
    close(p[0]);
    
    std::cout << "请输入->" << std::endl;
    std::string t;
    std::cin >> t;

    Write(p[1], t);
      
    close(p[1]);
    exit(0);
  }

  close(p[1]);
  
  int c = wait(nullptr);
  if (c < 0)
  {
     perror("wait error");
     return -1;
  }

  Read(p[0]);

  close(p[0]);
  return 0;
}
